package com.naiterui.ehp.bs.patient.service.impl;

import com.naiterui.common.repository.page.PageParamVO;
import com.naiterui.common.repository.page.PageVO;
import com.naiterui.ehp.bp.bo.notice.NoticeMessageBO;
import com.naiterui.ehp.bp.domain.NoticeMessage;
import com.naiterui.ehp.bs.patient.repository.INoticeMessageRepository;
import com.naiterui.ehp.bs.patient.service.INoticeMessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author luao
 * @date 2021/3/9 7:35 下午
 **/
@Service
@RequiredArgsConstructor
public class INoticeMessageServiceImpl implements INoticeMessageService {
    private final INoticeMessageRepository notificationRepository;

    @Override
    public PageVO<NoticeMessageBO> list(PageParamVO pageParam) {
        Page<NoticeMessage> page = notificationRepository.findByTypeAndDelFlagOrderByReleaseTimeDescCreatedAtDesc(NoticeMessage.TYPE_MANAGEMENT, 0, pageParam.getPageable());
        List<NoticeMessage> noticeMessageList = page.getContent();
        if (CollectionUtils.isEmpty(noticeMessageList)) {
            return new PageVO<>();
        }
        return PageVO.newBuilder()
                .pageNo(pageParam.getPage())
                .pageSize(pageParam.getNum())
                .totalCount((int) page.getTotalElements())
                .result(noticeMessageList.stream().map(noticeMessage ->
                        NoticeMessageBO.builder()
                                .id(noticeMessage.getId())
                                .title(noticeMessage.getTitle())
                                .releaseTime(noticeMessage.getReleaseTime())
                                .build()
                ).collect(Collectors.toList()))
                .build();
    }

    @Override
    public NoticeMessageBO detail(Long id) {
        Optional<NoticeMessage> optional = notificationRepository.findById(id);
        if (!optional.isPresent()) {
            return null;
        }
        NoticeMessage noticeMessage = optional.get();
        return NoticeMessageBO.builder()
                .id(noticeMessage.getId())
                .title(noticeMessage.getTitle())
                .content(noticeMessage.getContent())
                .releaseTime(noticeMessage.getReleaseTime())
                .build();
    }
}
